package com.agriculture.controller;

import com.agriculture.common.OrderStatus;
import com.agriculture.common.R;
import com.agriculture.entity.User;
import com.agriculture.service.OrderService;
import com.agriculture.entity.Orders;
import com.agriculture.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 订单
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;


    /**
     * 查询所有用户的所有订单
     * @return
     */
    @GetMapping("/list")
    public R getAllOrders(){
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        return R.success(orderService.list(queryWrapper));
    }

    /**
     * 查询当前用户的全部订单
     * @return
     */
    @GetMapping
    public R getAllOrdersByUserId(@RequestParam String token){
        User user = JwtUtils.parseToken(token);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, user.getId());
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        return R.success(orderService.list(queryWrapper));
    }

    /**
     * 根据 token 返回数据
     * @param token
     * @return
     */
    @GetMapping("/getByToken")
    public R getByToken(String token, Integer status){
        User user = JwtUtils.parseToken(token);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Orders::getUserId, user.getId());
        queryWrapper.eq(Orders::getStatus, status);

        Orders orderOne = orderService.getOne(queryWrapper);
        if(orderOne == null){
            Orders orders = new Orders();
            orders.setStatus(OrderStatus.ToBePaid);
            orders.setUserId(user.getId());
            orderService.save(orders);
            return R.success(orders);
        }else{
            return R.success(orderOne);
        }
    }


    /**
     * 修改订单
     * @param orders
     * @return
     */
    @PutMapping
    public R updateOrder(@RequestBody Orders orders){
        if(orders.getStatus()!=null && orders.getStatus() == OrderStatus.COMPLETED){
            // starus == 4 完成
            Date date = new Date();
            orders.setOrderNumber(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        }
        orderService.updateById(orders);
        return R.success(orders.getOrderNumber());
    }

}




